package com.hcinfos.gsoo.ui;

import java.util.ArrayList;
import java.util.List;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.json.JSONObject;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.text.format.DateUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.LocationClient;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.hcinfos.gsoo.GsooApplication;
import com.hcinfos.gsoo.R;
import com.hcinfos.gsoo.adapter.DingzuoListAdapter;
import com.hcinfos.gsoo.adapter.TypeGridViewAdapter;
import com.hcinfos.gsoo.adapter.TypeSingleSelectAdapter;
import com.hcinfos.gsoo.adapter.WaimaiListAdapter;
import com.hcinfos.gsoo.config.Urls;
import com.hcinfos.gsoo.enity.City;
import com.hcinfos.gsoo.enity.GdSupplerBasicConfExt;
import com.hcinfos.gsoo.service.LocationService;
import com.hcinfos.gsoo.util.LogUtil;
import com.hcinfos.gsoo.util.SharePreferenceUtil;
import com.hcinfos.gsoo.util.UtilHttp;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

public class DingzuoListActivity extends Activity implements OnClickListener {

	private ImageView back_iv;
	private PullToRefreshListView shopListView;
	private DingzuoListAdapter dingzuoListAdapter;
	private List<GdSupplerBasicConfExt> list;
	private List<GdSupplerBasicConfExt> totalList;
	private RelativeLayout tc_select_category_layout;
	private ListView tc_select_single_listview;
	private RelativeLayout tv_select1_rl;
	private RelativeLayout tv_select2_rl;
	private RelativeLayout tv_select3_rl;
	private ProgressBar progress;

	private TypeSingleSelectAdapter typeSingleSelectAdapter;
	private List<String> sortList;
	private List<String> sendList;// 配送数据列表
	private GridView typeGridView;
	private TypeGridViewAdapter gridAdapter;
	private List<String> gridList;
	private List<Integer> icons;

	private Intent intent;
	private SharePreferenceUtil util;
	private City city;
	private ObjectMapper mapper;

	public final int OBTAIN_DATA_SUCCESS = 0x2210;
	public final int OBTAIN_DATA_FAIL = OBTAIN_DATA_SUCCESS + 1;
	private LocationClient locationClient;
	private ImageView error_iv;

	private TextView tc_select2;
	private TextView tc_select3;
	private TextView tc_select1;

	private int typePosition = 0;// 类型排序
	private int sortPosition = 0; // 默认排序
	private int conPosition = 0;// 配送费排序

	private int page = 1;
	private int rows = 10;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_dingzuolist);
		locationClient = ((GsooApplication) getApplication()).mLocationClient;
		IntentFilter filter = new IntentFilter(LocationService.LOCATION_ACTION);
		registerReceiver(locationReceiver, filter);
		mapper = new ObjectMapper();
		initRes();
		util = new SharePreferenceUtil(this, "setting");
		city = (City) util.loadObject("city");
		if (city != null) {
			LogUtil.d("wxf", city.getName());
			if (GsooApplication.lat != null) {
				obtainList();
			} else {
				locationClient.start();
			}
		}

	}

	private boolean isLoadEnd = false;

	private void initRes() {
		tc_select3 = (TextView) findViewById(R.id.tc_select3);
		tc_select1 = (TextView) findViewById(R.id.tc_select1);
		tc_select2 = (TextView) findViewById(R.id.tc_select2);
		error_iv = (ImageView) findViewById(R.id.error_iv);
		progress = (ProgressBar) findViewById(R.id.progress);
		totalList = new ArrayList<GdSupplerBasicConfExt>();
		list = new ArrayList<GdSupplerBasicConfExt>();
		back_iv = (ImageView) findViewById(R.id.back_iv);
		back_iv.setOnClickListener(this);
		shopListView = (PullToRefreshListView) findViewById(R.id.shopListView);
		dingzuoListAdapter = new DingzuoListAdapter(this, list);
		shopListView.setAdapter(dingzuoListAdapter);
		shopListView.setOnItemClickListener(shopListOnItemClickListener);
		tc_select_category_layout = (RelativeLayout) findViewById(R.id.tc_select_category_layout);
		tc_select_single_listview = (ListView) findViewById(R.id.tc_select_single_listview);
		tc_select_category_layout.setOnTouchListener(typeSelectTouchListener);
		tv_select3_rl = (RelativeLayout) findViewById(R.id.tv_select3_rl);
		tv_select3_rl.setOnClickListener(this);
		tv_select2_rl = (RelativeLayout) findViewById(R.id.tv_select2_rl);
		tv_select2_rl.setOnClickListener(this);
		tv_select1_rl = (RelativeLayout) findViewById(R.id.tv_select1_rl);
		tv_select1_rl.setOnClickListener(this);

		shopListView.setOnRefreshListener(new OnRefreshListener<ListView>() {
			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				String label = DateUtils.formatDateTime(
						getApplicationContext(), System.currentTimeMillis(),
						DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE
								| DateUtils.FORMAT_ABBREV_ALL);
				// Update the LastUpdatedLabel
				refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
				page = 1;
				list.clear();
				totalList.clear();
				dingzuoListAdapter.setDataChange(totalList);
				obtainList();

			}
		});

		shopListView
				.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {

					@Override
					public void onLastItemVisible() {

						if (isLoadEnd) {
							return;
						}
						obtainList();
					}
				});
		sortList = new ArrayList<String>();
		sortList.add("默认排序");
		sortList.add("销量最高");
		sortList.add("起送价最低");
		sendList = new ArrayList<String>();
		sendList.add("配送费不限");
		sendList.add("免配送费");
		sendList.add("无起送金额");
		typeSingleSelectAdapter = new TypeSingleSelectAdapter(this, sortList);
		tc_select_single_listview.setAdapter(typeSingleSelectAdapter);
		tc_select_single_listview.setOnItemClickListener(typeItemClickListener);

		gridList = new ArrayList<String>();
		gridList.add("口味不限");
		gridList.add("中式快餐");
		gridList.add("西式快餐");
		gridList.add("日韩料理");
		gridList.add("面食点心");
		gridList.add("蛋糕面包");
		gridList.add("奶茶甜品");
		gridList.add("特色小吃");
		gridList.add("水果蔬菜");
		gridList.add("烧烤烤串");
		gridList.add("火锅");

		icons = new ArrayList<Integer>();
		icons.add(R.drawable.gsoo_takeout_store_cate_taste_all_notselected);
		icons.add(R.drawable.gsoo_takeout_store_cate_taste_cncook_notselected);
		icons.add(R.drawable.gsoo_takeout_store_cate_taste_cnfast_notselected);
		icons.add(R.drawable.gsoo_takeout_store_cate_taste_westfast_notselected);

		icons.add(R.drawable.gsoo_takeout_store_cate_taste_jprest_notselected);
		icons.add(R.drawable.gsoo_takeout_store_cate_taste_noodle_notselected);
		icons.add(R.drawable.gsoo_takeout_store_cate_taste_cake_notselected);
		icons.add(R.drawable.gsoo_takeout_store_cate_taste_dessert_notselected);

		icons.add(R.drawable.gsoo_takeout_store_cate_taste_snack_notselected);
		icons.add(R.drawable.gsoo_takeout_store_cate_taste_fruit_notselected);
		icons.add(R.drawable.gsoo_takeout_store_cate_taste_bbq_notselected);
		icons.add(R.drawable.gsoo_takeout_store_cate_taste_all_notselected);

		typeGridView = (GridView) findViewById(R.id.typeGridView);
		gridAdapter = new TypeGridViewAdapter(this, gridList, icons);
		typeGridView.setAdapter(gridAdapter);
		typeGridView.setOnItemClickListener(gridTypeClickListener);
	}

	OnTouchListener typeSelectTouchListener = new OnTouchListener() {
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			tc_select_category_layout.setVisibility(View.GONE);
			return true;

		}
	};

	OnItemClickListener typeItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1,
				int selectPosition, long arg3) {
			page = 1;
			tc_select_category_layout.setVisibility(View.GONE);
			tc_select_single_listview.setVisibility(View.GONE);
			if (selectType == 1) {
				sortPosition = selectPosition;
				tc_select2.setText(sortList.get(selectPosition));
			} else if (selectType == 2) {
				conPosition = selectPosition;
				tc_select3.setText(sendList.get(conPosition));
			}

			obtainList();
		}
	};
	OnItemClickListener gridTypeClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			page = 1;
			tc_select_single_listview.setVisibility(View.GONE);
			typeGridView.setVisibility(View.GONE);
			tc_select_category_layout.setVisibility(View.GONE);
			typePosition = arg2;
			tc_select1.setText(gridList.get(arg2));
			// if (arg2 == 2) {
			// flavor = 1;
			// }
			flavor = arg2;
			if (arg2 == 0) {
				flavor = -2;
			}

			progress.setVisibility(View.VISIBLE);
			error_iv.setVisibility(View.GONE);
			obtainList();
		}
	};

	BroadcastReceiver locationReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {

			obtainList();
		}

	};
	private int selectType = 0;

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unregisterReceiver(locationReceiver);
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.back_iv:
			finish();
			break;
		case R.id.tv_select1_rl:
			selectType = 0;
			tc_select_category_layout.setVisibility(View.VISIBLE);
			tc_select_single_listview.setVisibility(View.GONE);
			typeGridView.setVisibility(View.VISIBLE);
			break;
		case R.id.tv_select2_rl:
			selectType = 1;
			typeGridView.setVisibility(View.GONE);
			tc_select_category_layout.setVisibility(View.VISIBLE);
			typeSingleSelectAdapter.setDataChange(sortList);
			tc_select_single_listview.setVisibility(View.VISIBLE);
			break;
		case R.id.tv_select3_rl:
			selectType = 2;
			tc_select_category_layout.setVisibility(View.VISIBLE);
			tc_select_single_listview.setVisibility(View.VISIBLE);
			typeSingleSelectAdapter.setDataChange(sendList);
			typeGridView.setVisibility(View.GONE);
			break;
		}
	}

	OnItemClickListener shopListOnItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position,
				long arg3) {
			int curPosition = position - 1;
			if (curPosition >= 0 && curPosition < totalList.size()) {
				intent = new Intent(DingzuoListActivity.this,
						MenuActivity.class);
				intent.putExtra("type", 0);// 0 表示订座 1 表示 订餐
				intent.putExtra("detail", totalList.get(curPosition));
				startActivity(intent);
			}

		}
	};

	private String distance = "10";
	private String sortStr = "order_sum desc," + distance;
	private String sortPrice = "";
	private int flavor = 0;

	private void obtainList() {
		shopListView.setVisibility(View.GONE);
		totalList.clear();
		LogUtil.d("wxf", "GsooApplication.lng=" + GsooApplication.lng
				+ ", GsooApplication.lat=" + GsooApplication.lat);
		HttpUtils http = UtilHttp.getHttpUtils(this);
		RequestParams params = new RequestParams();
		params.addBodyParameter("_lon", GsooApplication.lng + "");
		params.addBodyParameter("_lat", GsooApplication.lat + "");
		params.addBodyParameter("_city", city.getCityId());
		params.addBodyParameter("_km", distance + "");
		params.addBodyParameter("_order", sortStr);
		params.addBodyParameter("_ot_state", "1");
		params.addBodyParameter("page", page + "");
		params.addBodyParameter("rows", rows + "");
		if (flavor != 0) {
			params.addBodyParameter("_flavor", flavor + "");
		}
		http.send(HttpRequest.HttpMethod.POST, Urls.getSupplerBasic, params,
				new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						LogUtil.e("wxf", arg0.toString());
						handler.sendEmptyMessage(OBTAIN_DATA_FAIL);
					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						String result = arg0.result;
						LogUtil.d("wxf", result);
						try {
							JSONObject obj = new JSONObject(result);
							int state = obj.getInt("state");
							if (state == 200) {
								list = mapper.readValue(
										obj.getString("rows"),
										new TypeReference<List<GdSupplerBasicConfExt>>() {
										});
								handler.sendEmptyMessage(OBTAIN_DATA_SUCCESS);
							} else {
								handler.sendEmptyMessage(OBTAIN_DATA_FAIL);

							}
						} catch (Exception e) {
							LogUtil.e("wxf", e.toString());
							handler.sendEmptyMessage(OBTAIN_DATA_FAIL);

						}

					}
				});
	}

	Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {
			progress.setVisibility(View.GONE);
			shopListView.setVisibility(View.VISIBLE);
			switch (msg.what) {
			case OBTAIN_DATA_FAIL:
				error_iv.setVisibility(View.VISIBLE);
				shopListView.setVisibility(View.GONE);
				break;
			case OBTAIN_DATA_SUCCESS:
				if (list != null) {
					if (list.size() < rows) {

						isLoadEnd = true;
					} else {
						isLoadEnd = false;
						page += 1;
					}
					totalList.addAll(list);
					dingzuoListAdapter.setDataChange(totalList);
				}
				if (totalList.size() == 0) {
					shopListView.setVisibility(View.GONE);
					error_iv.setVisibility(View.VISIBLE);
					Toast.makeText(DingzuoListActivity.this, "暂无数据", 500)
							.show();
				}
				shopListView.onRefreshComplete();
				break;
			}
		};
	};
}
